package socket;

import sun.nio.ch.ThreadPool;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *服务端
 */
public class Server {
    /**
     * 192.168.1.248
     * java.net.ServerSocket
     * 运行在服务端，用于开启服务端端口，并等待客户端链接。
     * 如果我们将Socket比喻为“插座”,那么ServerSocket相当于“总机”
     *
     * */
    private ServerSocket serverSocket;
    private ExecutorService threadPool;
    public Server() {
        try {
            System.out.println("正在启动服务器...");
            /**
             * 创建ServerSocket时要指定服务器端口，改端口不能与其他程序一致，否则会抛出异常
             * java。net.BindException:address already in use
             * 此时只能更换其他端口或者将该端口占用程序关闭
             * */
            serverSocket=new ServerSocket(8087);
            threadPool= Executors.newFixedThreadPool(30);
            System.out.println("服务器启动完毕");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        try {
            while (true) {

                System.out.println("等待客户连接....");
                Socket socket = serverSocket.accept();
                System.out.println("一个客户连接成功了");
                //启动一个线程，；来处理客户端的交互
                ClientHandler handler=new ClientHandler(socket);
//                Thread t=new Thread(handler);
//                t.start();
                threadPool.execute(handler);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server server=new Server();
        server.start();
    }
    private class ClientHandler implements Runnable{
        private Socket socket;
        public ClientHandler(Socket socket) {
            this.socket=socket;
        }

        public void run(){
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                String message;
                while ((message = br.readLine()) != null) {
                    System.out.println("客户端说：" + message);

                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
